package com.vcredit.creditcat.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import com.vcredit.creditcat.framework.util.AntUrlPathMatcher;
import com.vcredit.creditcat.framework.util.UrlMatcher;
/**
 * 用于加载所有用户角色
 *
 */
@Service("invocationSecurityMetadataSourceService")
public class InvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource{
	private static Map<String, Collection<ConfigAttribute>> resourceMap;
	private UrlMatcher urlMatcher = new AntUrlPathMatcher(); 
	@Autowired
	private RoleService roleService;
	/**
	 * 从数据库加载资源与角色的MAP集合
	 */
	public  void loadResourceDefine(){
		resourceMap = roleService.getResourceMap();
	}
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}
	/**
	 * 把resourceMap封装成Collection对象返回
	 */
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		Collection<ConfigAttribute> returnCollection = new ArrayList<ConfigAttribute>(); 
		String url = ((FilterInvocation) object).getRequestUrl();   
		Iterator<String> ite = resourceMap.keySet().iterator();   
        while (ite.hasNext()) {   
            String resURL = ite.next();  
           if(resURL!=null&&url!=null){
	            if (urlMatcher.pathMatchesUrl(resURL, url)) {   
	            	returnCollection.addAll(resourceMap.get(resURL));   
	            }   
           }
        }   
        return returnCollection.size()==0?null:returnCollection;
	}

	public boolean supports(Class<?> arg0) {
		return true;
	}
	public static void main(String[] args) {
		UrlMatcher urlMatcher = new AntUrlPathMatcher();
		System.out.println(urlMatcher.pathMatchesUrl("/**", "/card/changeShow.do"));
	}
}
